package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleCollectionMapper;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.exception.CustomException;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;

import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.dtos.CollectionBehaviorDto;
import com.heima.model.article.mess.ArticleVisitStreamMess;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleCollection;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.comment.dtos.CommentPageDto;
import com.heima.model.comment.dtos.StatusCommentDto;
import com.heima.model.comment.vos.ArticleCommnetVo;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsStatisticsDto;
import com.heima.utils.common.DateUtils;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.nntp.Article;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


@Service
@Transactional
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    // 单页最大加载的数字
    private final static short MAX_PAGE_SIZE = 50;

    @Autowired
    private ApArticleCollectionMapper apArticleCollectionMapper;

    @Autowired
    private CacheService cacheService;

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private ArticleFreemarkerServiceImpl articleFreemarkerService;

    /**
     * 根据参数加载文章列表
     *
     * @param loadtype 1为加载更多  2为加载最新
     * @param dto
     * @return
     */

    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDto dto) {

        if (dto == null && loadtype == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //1.校验参数
        Integer size = dto.getSize();
        if (size == null || size <= 0) {
            size = 10;
        }
        size = Math.min(size, MAX_PAGE_SIZE);
        dto.setSize(size);

        //类型参数检验
        if (!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_MORE) && !loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW)) {
            loadtype = ArticleConstants.LOADTYPE_LOAD_MORE;
        }

        //文章频道校验
        if (StringUtils.isEmpty(dto.getTag())) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }

        //时间校验
        if (dto.getMaxBehotTime() == null) dto.setMaxBehotTime(new Date());
        if (dto.getMinBehotTime() == null) dto.setMinBehotTime(new Date());
        //2.查询数据
        List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, loadtype);

        //3.结果封装
        ResponseResult responseResult = ResponseResult.okResult(apArticles);
        return responseResult;
    }


    /**
     * 加载首页
     *
     * @param dto
     * @param type
     * @return
     */
    @Override
    public ResponseResult loadFirstPage(ArticleHomeDto dto, Short type) {
        //首页：优先推荐缓存中的热点文章数据
        //如果缓存中没有，那再去查数据库
        String articleJson = cacheService.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
        if (StringUtils.isNotEmpty(articleJson)) {
            List<HotArticleVo> list = JSON.parseArray(articleJson, HotArticleVo.class);
//            List<ApArticle> apArticles = new ArrayList<>();
//            for (HotArticleVo hotArticleVo : list) {
//                ApArticle apArticle = new ApArticle();
//                BeanUtils.copyProperties(hotArticleVo,apArticle);
//                apArticles.add(apArticle);
//            }
//            return ResponseResult.okResult(apArticles);
            return ResponseResult.okResult(list);
        } else {
            return load(type, dto);
        }
    }

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    /**
     * 保存app端相关文章
     *
     * @param dto
     * @return
     */
//    @Async
    @Override
    public ResponseResult saveArticle(ArticleDto dto) {
        //1.检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto, apArticle);

        //2.判断是否存在id
        if (dto.getId() == null) {
            //2.1 不存在id  保存  文章  文章配置  文章内容

            //保存文章
            save(apArticle);

            //保存配置
            ApArticleConfig apArticleConfig = new ApArticleConfig(apArticle.getId());
            apArticleConfigMapper.insert(apArticleConfig);

            //保存 文章内容
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.insert(apArticleContent);

        } else {
            //2.2 存在id   修改  文章  文章内容

            //修改  文章
            updateById(apArticle);

            //修改文章内容
            ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, dto.getId()));
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.updateById(apArticleContent);
        }

        //异步调用 生成静态文件上传到minio中
        articleFreemarkerService.buildArticleToMinIO(apArticle, dto.getContent());
        //3.结果返回  文章的id
        return ResponseResult.okResult(apArticle.getId());
    }

    /**
     * 用户行为回显
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {
        //0.检查参数
        if (dto == null || dto.getArticleId() == null || dto.getAuthorId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Integer userID = AppThreadLocalUtil.getUserID();
        if (userID == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //喜欢行为
        Boolean islike = cacheService.get(userID + dto.getArticleId() + BehaviorConstants.LIKE_BEHAVIOR) != null;

        //不喜欢的行为
        Boolean isunlike = cacheService.get(userID + dto.getArticleId() + BehaviorConstants.UN_LIKE_BEHAVIOR) != null;

        //是否收藏
        Boolean iscollection = cacheService.get(userID + dto.getArticleId() + BehaviorConstants.COLLECTION_BEHAVIOR) != null;

        //是否关注
        Boolean isfollow = cacheService.get(userID + dto.getArticleId() + BehaviorConstants.APUSER_FOLLOW_RELATION) != null;

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("isfollow", isfollow);
        resultMap.put("islike", islike);
        resultMap.put("isunlike", isunlike);
        resultMap.put("iscollection", iscollection);

        return ResponseResult.okResult(resultMap);
    }

    /**
     * 用户收藏
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult collectionBehavior(CollectionBehaviorDto dto) {
        //检查参数
        //0.检查参数
        if (dto == null || dto.getEntryId() == null || dto.getPublishedTime() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Integer userID = AppThreadLocalUtil.getUserID();
        if (userID == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取文章详细信息
        ApArticle apArticle = getOne(Wrappers.<ApArticle>lambdaQuery().eq(ApArticle::getId, dto.getEntryId()));

        //判断用户是否已经收藏
        Integer count = apArticleCollectionMapper.selectCount(Wrappers.<ApArticleCollection>lambdaQuery()
                .eq(ApArticleCollection::getUserId, userID)
                .eq(ApArticleCollection::getArticleId, dto.getEntryId()));


        if (count > 0) {
            //用户已收藏取消收藏
            //删除用户关注信息
            apArticleCollectionMapper.delete(Wrappers.<ApArticleCollection>lambdaQuery()
                    .eq(ApArticleCollection::getUserId, userID)
                    .eq(ApArticleCollection::getArticleId, dto.getEntryId()));

            //文章收藏数减一
            apArticle.setCollection(apArticle.getCollection() - 1);
            apArticleMapper.updateById(apArticle);

            //删除用户行为
            cacheService.delete(userID + dto.getEntryId() + BehaviorConstants.COLLECTION_BEHAVIOR);
        } else {
            //用户未收藏添加收藏
            //添加收藏信息
            ApArticleCollection apArticleCollection = ApArticleCollection.builder()
                    .userId(userID)
                    .articleId(dto.getEntryId())
                    .collectionTime(new Date())
                    .publishedTime(dto.getPublishedTime())
                    .type(dto.getType())
                    .build();
            System.out.println(apArticleCollection);
            apArticleCollectionMapper.insert(apArticleCollection);

            //文章收藏数加一
            apArticle.setCollection(apArticle.getCollection() + 1);
            apArticleMapper.updateById(apArticle);
            //添加用户行为
            cacheService.set(userID + dto.getEntryId() + BehaviorConstants.COLLECTION_BEHAVIOR, userID.toString());
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 更新文章的分值  同时更新缓存中的热点文章数据
     *
     * @param mess
     */
    @Override
    public void updateScore(ArticleVisitStreamMess mess) {
        //1.更新文章的阅读、点赞、收藏、评论的数量
        ApArticle apArticle = updateArticle(mess);
        //2.计算文章的分值
        Integer score = computeScore(apArticle);
        score *= 3;

        //3.替换当前文章对应频道的热点数据
        replaceDataToRedis(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + apArticle.getChannelId());

        //4.替换推荐对应的热点数据
        replaceDataToRedis(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);

    }

    /**
     * 替换数据并且存入到redis
     *
     * @param apArticle
     * @param score
     * @param channelId
     */
    private void replaceDataToRedis(ApArticle apArticle, Integer score, String channelId) {
        String articleListStr = cacheService.get(channelId);
        if (StringUtils.isNotBlank(articleListStr)) {
            List<HotArticleVo> hotArticleVoList = JSON.parseArray(articleListStr, HotArticleVo.class);

            boolean flag = true;

            //如果缓存中存在该文章，只更新分值
            for (HotArticleVo hotArticleVo : hotArticleVoList) {
                if (hotArticleVo.getId().equals(apArticle.getId())) {
                    hotArticleVo.setScore(score);
                    flag = false;
                    break;
                }
            }

            //如果缓存中不存在，查询缓存中分值最小的一条数据，进行分值的比较，如果当前文章的分值大于缓存中的数据，就替换
            if (flag) {
                if (hotArticleVoList.size() >= 30) {
                    hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
                    HotArticleVo lastHot = hotArticleVoList.get(hotArticleVoList.size() - 1);
                    if (lastHot.getScore() < score) {
                        hotArticleVoList.remove(lastHot);
                        HotArticleVo hot = new HotArticleVo();
                        BeanUtils.copyProperties(apArticle, hot);
                        hot.setScore(score);
                        hotArticleVoList.add(hot);
                    }


                } else {
                    HotArticleVo hot = new HotArticleVo();
                    BeanUtils.copyProperties(apArticle, hot);
                    hot.setScore(score);
                    hotArticleVoList.add(hot);
                }
            }
            //缓存到redis
            hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
            cacheService.set(channelId, JSON.toJSONString(hotArticleVoList));

        }
    }

    /**
     * 更新文章行为数量
     *
     * @param mess
     */
    private ApArticle updateArticle(ArticleVisitStreamMess mess) {
        ApArticle apArticle = getById(mess.getArticleId());
        apArticle.setCollection(apArticle.getCollection() == null ? mess.getCollect() : apArticle.getCollection() + mess.getCollect());
        apArticle.setComment(apArticle.getComment() == null ? mess.getComment() : apArticle.getComment() + mess.getComment());
        apArticle.setLikes(apArticle.getLikes() == null ? mess.getLike() : apArticle.getLikes() + mess.getLike());
        apArticle.setViews(apArticle.getViews() == null ? mess.getView() : apArticle.getViews() + mess.getView());
        updateById(apArticle);
        return apArticle;

    }

    /**
     * 计算文章的具体分值
     *
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        Integer score = 0;
        if (apArticle.getLikes() != null) {
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if (apArticle.getViews() != null) {
            score += apArticle.getViews();
        }
        if (apArticle.getComment() != null) {
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if (apArticle.getCollection() != null) {
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }

        return score;
    }

    /**
     * 查看文章统计
     *
     * @param wmUserId
     * @param beginDate
     * @param endDate
     * @return
     */
    public ResponseResult getNewsDimension(Integer wmUserId, Date beginDate, Date endDate) {
        //根据作者id,先后时间从数据库中拿到数据
        Map map = apArticleMapper.getNewsDimension(wmUserId, beginDate, endDate);
        return ResponseResult.okResult(map);
    }

    /**
     * 分页展示文章列表
     *
     * @param dto
     */
    public PageResponseResult getNewsPage(WmNewsStatisticsDto dto) {
        //根据工具类转换参数类型
        Date beginDate = DateUtils.stringToDate(dto.getBeginDate());
        Date endDate = DateUtils.stringToDate(dto.getEndDate());
        //分页校验
        dto.checkParam();
        //分页
        IPage page = new Page(dto.getPage(), dto.getSize());
        //根据作者id和时间查询相关数据
        LambdaQueryWrapper<ApArticle> select = Wrappers.<ApArticle>lambdaQuery()
                .eq(ApArticle::getAuthorId, dto.getWmUserId())
                .between(ApArticle::getPublishTime, beginDate, endDate)
                .select(ApArticle::getId, ApArticle::getTitle, ApArticle::getViews, ApArticle::getComment, ApArticle::getCollection, ApArticle::getLikes);
        //倒序
        select.orderByDesc(ApArticle::getPublishTime);
        page = page(page, select);
        //封装返回
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;

    }

    /**
     * 展示评论文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult showListComment(CommentPageDto dto) {

        Integer dtoPage = dto.getPage();

        dto.setPage((dto.getPage() - 1) * dto.getSize());
        List<ArticleCommnetVo> list = apArticleMapper.showListComment(dto);

        int count = apArticleMapper.showListCount(dto);

        PageResponseResult result = new PageResponseResult(dtoPage, dto.getSize(), count);
        result.setData(list);
        return result;
    }

    /**
     * 评论数修改
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatusComment(StatusCommentDto dto) {
        //1.参数检验
        if (dto.getArticleId() == null || dto.getOperation() != 0 && dto.getOperation() != 1) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
//        //2.查询当前文章数据
//        ApArticle article = apArticleMapper.selectById(dto.getArticleId());
//        if (article==null){
//            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
//        }
        //3.修改并保存
//        article.setComment(0);

        update(Wrappers.<ApArticle>lambdaUpdate()
                .eq(ApArticle::getId, dto.getArticleId())
                .set(ApArticle::getComment, 0));

        //4.配置表修改
        ApArticleConfig apArticleConfig = apArticleConfigMapper
                .selectOne(Wrappers
                        .<ApArticleConfig>lambdaUpdate()
                        .eq(ApArticleConfig::getArticleId, dto.getArticleId()));


        apArticleConfig.setIsComment(dto.getOperation() == 1);
        apArticleConfigMapper.updateById(apArticleConfig);
//        if (dto.getOperation().equals(0)) {
//            apArticleConfig.setIsComment(false);
//            apArticleConfigMapper.updateById(apArticleConfig);
//
//        } else {
//            apArticleConfig.setIsComment(true);
//            apArticleConfigMapper.updateById(apArticleConfig);
//        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 获取文章评论状态
     *
     * @param articleId
     * @return
     */
    @Override
    public Boolean getIsComment(Long articleId) {
        ApArticleConfig apArticleConfig = apArticleConfigMapper
                .selectOne(Wrappers
                        .<ApArticleConfig>lambdaUpdate()
                        .eq(ApArticleConfig::getArticleId, articleId));
        return apArticleConfig.getIsComment();
    }
}